<template>
  <div class="decimg" @click="close">
    <div class="box">
      <el-image :src="previewUrl" fit="scale-down">
        <div slot="placeholder" class="image-slot">
          <i class="el-icon-loading" />
        </div>
      </el-image>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      previewUrl: ''
    };
  },
  created() {
    this.previewUrl = this.src.indexOf(this.imgPrefix) === 0 ? this.src + this.imgSuffixMid : this.src;
  },
  mounted() {
    this.getMax();
    window.addEventListener('resize', this.getMax);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getMax);
  },
  methods: {
    // 关闭预览
    close(e) {
      if (e.target.className === 'decimg' || e.target.className === 'box') {
        this.$emit('close', false);
      }
    },
    getMax() {
      const width =
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;
      const height =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      const max = width > height ? height : width;
      // 20 留作四周边距
      document
        .querySelector('.box')
        .setAttribute('style', `width:${max - 20}px;height:${max - 20}px`);
    }
  }
};
</script>

<style lang="scss" scoped>
.decimg {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  .box {
    display: flex;
    align-items: center;
    .el-image {
      margin: 0 auto;
      font-size: 40px;
      color: #fff;
    }
    .el-image__error {
      width: 50px;
      height: 50px;
    }
  }
}
</style>
